﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace problema3
{
    //aceasta clasa poate fi considerata si Concrete Factory  din abstract factory pattern
    class ConnectionPool : Container        //patternur: iterator si singleton
    {
        private static ConnectionPool instance_ConnectionPool = new ConnectionPool();       //singleton

        private ConnectionPool()
	    {
            baze_de_date = new Hashtable(100);
            DataConnection d = new DataConnection();
            DataConnection d1 = new DataConnection();
            DataConnection d2 = new DataConnection();
            d.setdatabaseName("baza de date 1");
            baze_de_date.Add(1,d);
            d1.setdatabaseName("baza de date 2");
            baze_de_date.Add(2, d1);
            d2.setdatabaseName("baza de date 3");
            baze_de_date.Add(3, d2);
	    }
        public static ConnectionPool getInstance()
        {
            return instance_ConnectionPool;
        }

        static Hashtable baze_de_date;
        public DataConnection AcquireConnection(String databaseName)//metoda care va elimina conexiunea din lista de con a unei baze de date
        //pt a fi folosita de catre program%
        {
            foreach (DictionaryEntry de in baze_de_date)
            {
                if (((DataConnection)(de.Value)).getdatabaseName() == databaseName)
                {
                    baze_de_date.Remove(de.Key);
                    return (DataConnection)de.Value;
                }
            }

            return null;
        }

        public void ReleaseConnection(DataConnection dc)
        {
            for (int c = 1; c <= baze_de_date.Count; c++)
            {
                if (baze_de_date.ContainsKey(c) == false)
                    baze_de_date.Add(c, dc);
            }
        }


        public Iterator createIterator()            //iterator
        {
            DataConnectionIterator result = new DataConnectionIterator();
            return result;
        }

        //clasa DataConnetionIterator paote fi considerata clasa ConcreteProduct din abstract factory pattern
        private class DataConnectionIterator : Iterator //iterator
        {
            private int position=1;

            public Boolean hasnext()
            {
                if (position <= baze_de_date.Count)
                    return true;
                else
                    return false;
            }

            public DataConnection next()
            {
                if (this.hasnext())
                    return (DataConnection)(baze_de_date[position++]);
                else
                    return null;
            }

        }
    }
}
